//
//  FeedsListViewController.m
//  rss_reader
//
//  Created by Oleg Soldatoff on 4/13/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "FeedsListViewController.h"


@implementation FeedsListViewController

@synthesize base = _base;
@synthesize feedsArray = _feedsArray;
@synthesize siteID = _siteID;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
      self.base = [[[DataBase alloc] init]autorelease];

    }
    return self;
}

- (void) dealloc {
  [_base release];
  [super dealloc];
}

-(void) viewWillAppear:(BOOL)animated {
  [[NSNotificationCenter defaultCenter] addObserver:self 
                                           selector:@selector(pocessNotification:)  
                                               name:@"BaseUpdated" 
                                             object:nil];

  [super viewWillAppear:animated];
}


-(void) viewWillDisappear:(BOOL)animated {
  [[NSNotificationCenter defaultCenter] removeObserver:self]; 
  [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  
  self.title = NSLocalizedString(@"Feeds", @"Feeds");
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
  
  UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshRSS:)] autorelease];
  self.navigationItem.rightBarButtonItem = refreshButton;

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.base = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   // Return the number of rows in the section.
  
  if ( [self.feedsArray count] == 0 ) {
    self.feedsArray = [self.base baseFeedsForSiteID:self.siteID]; 
  }
  
  return [self.feedsArray count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
  
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //cell.indentationLevel = 4;
    
    
    UILabel *allReadNum = [[[UILabel alloc] initWithFrame:CGRectMake(250, 10, 40, 25)]autorelease];
    
    //[allReadNum setText:[NSString stringWithFormat:@"%d", newsBase.listOfAllReadNews.count]];
    [allReadNum setAutoresizesSubviews:YES];
    [allReadNum setTextAlignment:UITextAlignmentCenter];
    allReadNum.clipsToBounds = YES;
    allReadNum.layer.cornerRadius = 10.0f;
    [allReadNum setFont:[UIFont boldSystemFontOfSize:10]];
    [allReadNum setTextColor:[UIColor whiteColor]];
    [allReadNum setBackgroundColor:[UIColor grayColor]];
    allReadNum.tag = 888;
    [cell addSubview:allReadNum];

  }
      
  UILabel *numberToRead = (UILabel *) [cell viewWithTag:888];

  NSLog(@"%@", [[self.feedsArray objectAtIndex:indexPath.row] valueForKey:@"ID"]);
  
  numberToRead.text = [NSString stringWithFormat:@"%@", 
                       [self.base newArticlesForFeedID: [[self.feedsArray objectAtIndex:indexPath.row] valueForKey:@"ID"]]];
//  
    // Configure the cell...
  cell.textLabel.text = [[self.feedsArray objectAtIndex:indexPath.row] valueForKey:@"NAME"];
  
  return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
  MasterViewController *masterViewController = [[MasterViewController alloc] init];
  masterViewController.title = [[self.feedsArray objectAtIndex:indexPath.row]valueForKey:@"NAME"];
  masterViewController.feedID = [[[self.feedsArray objectAtIndex:indexPath.row]valueForKey:@"ID"]intValue]; 
  [self.navigationController pushViewController:masterViewController animated:YES];
  [masterViewController release];
     
}

- (void) pocessNotification:(NSNotification *) notification { 
  
  if ( [[notification name] isEqualToString:@"BaseUpdated"] )  {
    self.feedsArray = nil;
    [self.tableView reloadData]; 
  }
} 

- (void) refreshRSS: (id) sender {

  [[[[DataBase alloc]init]autorelease]updateAllFromInet];
  
}


@end
